#!/bin/bash

RUN_DIR=$(pwd)
PATCH_DIR=${RUN_DIR}/patches
BUILDWORK_DIR=${RUN_DIR}/buildwork
SRC_DIR=${BUILDWORK_DIR}/src

# 获取用户输入的构建目录名称，默认值为 build_hi3093
read -t 15 -p "Please enter the build directory name (default is build_hi3093): " BUILD_DIR_NAME
BUILD_DIR_NAME=${BUILD_DIR_NAME:-build_hi3093}

# 询问是否需要QT组件
read -t 15 -p "Do you need QT component? (yes/no, default is yes): " QT_INPUT
QT_INPUT=${QT_INPUT:-yes}
QT_INPUT=$(echo "$QT_INPUT" | tr '[:upper:]' '[:lower:]')
if [[ "$QT_INPUT" == "yes" || "$QT_INPUT" == "y" ]]; then
    QT_FLAG="-f openeuler-qt"
fi

# 询问是否需要使用Uniproton
read -t 15 -p "Do you need UniProton? (yes/no, default is yes): " MCS_INPUT
MCS_INPUT=${MCS_INPUT:-yes}
MCS_INPUT=$(echo "$MCS_INPUT" | tr '[:upper:]' '[:lower:]')
if [[ "$MCS_INPUT" == "yes" || "$MCS_INPUT" == "y" ]]; then
    MCS_FLAG="-f openeuler-mcs"
fi


while [ -d "${BUILDWORK_DIR}/build/${BUILD_DIR_NAME}" ]; do
    echo "The directory ${BUILD_DIR_NAME} already exists."
    if [[ "${BUILD_DIR_NAME}" =~ _[0-9]+$ ]]; then
        BUILD_DIR_NAME=$(echo "${BUILD_DIR_NAME}" | sed -E 's/_[0-9]+$/_'"$(( ${BASH_REMATCH[1]} + 1 ))"'/')
    else
        BUILD_DIR_NAME="${BUILD_DIR_NAME}_2"
    fi
done

BUILD_DIR=${BUILDWORK_DIR}/build/${BUILD_DIR_NAME}


if [ -d "${BUILDWORK_DIR}" ]; then
    echo "The buildwork directory already exists. Skipping initialization and update."
    cd ${BUILDWORK_DIR}
else
    # 初始化并更新 buildwork 目录
    oebuild init buildwork
    cd ${BUILDWORK_DIR}
    oebuild update || { echo "Failed to update buildwork"; exit 1; }
    wait
fi

# 生成构建文件
cd ${BUILDWORK_DIR}
oebuild generate -p hi3093 $QT_FLAG $MCS_FLAG -d ${BUILD_DIR_NAME}

# 下载3093源码并重命名目录
cd ${SRC_DIR}
if [ ! -d "mpu_solution" ]; then
    git clone https://gitee.com/openeuler/hi-mpu.git || { echo "Failed to clone repository"; exit 1; }
    mv hi-mpu/ mpu_solution
fi

cd ${SRC_DIR}/mpu_solution/build/build_fs
if ! grep -q "insmod /lib/modules/hi3093/gmac_drv.ko" hi3093_init.sh; then
  sed -i 's|insmod /lib/modules/gmac_drv.ko|insmod /lib/modules/hi3093/gmac_drv.ko|' hi3093_init.sh
fi

cd ${SRC_DIR}/yocto-meta-openeuler
patch -p1 -N < ${PATCH_DIR}/hisilicon-qt-mouse-defconfig.patch

cd ${BUILD_DIR}
sed -i '/  DISTRO_FEATURES:append = " mcs"/a \ \ DISTRO_FEATURES:append = " mpu_solution "' compile.yaml

oebuild bitbake